package server

import (
	"leechbox_gis/apis"
	"leechbox_gis/models"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
	"github.com/sirupsen/logrus"
)

var instance *iris.Application

// 初始化
func initBackend() {
	instance = iris.New()
	instance.Logger().SetLevel("info")
	instance.Logger().SetTimeFormat("2006-01-02 15:04:05")
	instance.Use(recover.New())
	instance.Use(logger.New())
	instance.Use(cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{iris.MethodGet, iris.MethodPost, iris.MethodDelete, iris.MethodPut},
		AllowedHeaders:   []string{"*"},
		MaxAge:           60,
		AllowCredentials: true,
	}))
}

func configBackend() {
	instance.OnAnyErrorCode(func(context iris.Context) {
		path := context.Path()
		if strings.Contains(path, "/") {
			_, _ = context.JSON(&models.ResponseBody{
				Code:    context.GetStatusCode(),
				Message: "",
			})
		}
	})

	instance.Any("/", func(context iris.Context) {
		_, _ = context.JSON(&models.ResponseBody{
			Code:    200,
			Message: "Powered by afterloe <liumin@ascs.tech>",
		})
	})

	// 公用路由
	mvc.Configure(instance.Party("/"), func(pub *mvc.Application) {
		pub.Party("/").Handle(new(apis.PublicAPI))
	})

	// 鉴权 api
	mvc.Configure(instance.Party("/aip"), func(aip *mvc.Application) {
		aip.Party("/execute").Handle(new(apis.ExecuteAPI))
		// aip.Party("/app/{name:string}").Handle(new(routes.AppRoute))
	})
}

func signalListener(server *http.Server) {
	pkg := make(chan os.Signal)
	signal.Notify(pkg, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
	go func() {
		code := <-pkg
		logrus.Infof("得到信号 [%s], 即将退出服务", code)
		logrus.Info("服务关闭")
		os.Exit(0)
	}()
}

func StartUpBackend() {
	initBackend()
	configBackend()
	instanceService := &http.Server{
		Addr: "0.0.0.0:8085",
	}
	signalListener(instanceService)
	if err := instance.Run(iris.Server(instanceService), iris.WithConfiguration(iris.Configuration{
		DisableStartupLog:                 false,
		DisableInterruptHandler:           false,
		DisablePathCorrection:             false,
		EnablePathEscape:                  false,
		FireMethodNotAllowed:              false,
		DisableBodyConsumptionOnUnmarshal: false,
		DisableAutoFireStatusCode:         false,
		RemoteAddrHeaders:                 map[string]bool{"X-Forwarded-For": true},
		EnableOptimizations:               true,
		TimeFormat:                        "2006-01-02 15:04:05",
		Charset:                           "UTF-8",
	})); nil != err {
		logrus.Error(err)
		os.Exit(-2)
	}
}
